// 排期相关
// 按月获取订单数量
const cloud = require('wx-server-sdk')
const moment = require('moment')
const got = require('got');
cloud.init({
  env: cloud.DYNAMIC_CURRENT_ENV,
  throwOnNotFound: false
})
const db = cloud.database();
const _ = db.command;
const $ = _.aggregate;

getAgenda = event => {
  console.log(event);
  const month = event.month || moment().format("YYYY-MM");
  // 两种情况：按工作室，按人
  const studioid = event.studioid;
  const teamid = event.teamid;
  let where = {
    studioid: studioid,
    'team._id': teamid,
    status: 0,
    date: db.RegExp({
      regexp: `${month}-`,
      options: '',
    })
  };
  return db.collection('agenda').aggregate().match(where).group({
    _id: '$date',
    num: $.sum(1) // TODO 订单有状态？
  }).sort({
    _id: 1
  }).end();
}

addAgenda = event => {

}

// 设置排期
setAgenda = async (event) => {
  let agenda = event.agenda;
  console.log(agenda);
  // agenda._id = agenda.orderid;
  const transaction = await db.startTransaction();
  var result2;
  if (!agenda._id) {
    agenda._id = agenda.orderid;
    result2 = await transaction.collection('agenda').add({
      data: agenda
    });
  } else {
    delete agenda._id;
    result2 = await transaction.collection('agenda').doc(agenda.orderid).update({
      data: agenda
    });
  }

  console.log(result2);
  const orderid = agenda.orderid;
  delete agenda.studioid;
  delete agenda.orderid;
  delete agenda._id;
  let result = await transaction.collection('order').doc(orderid).update({
    data: {
      status: 2,
      agenda: agenda,
      logs: _.push({
        time: moment().format("YYYY-MM-DD HH:MM:SS"),
        user: agenda.user,
        text: `排期拍摄`
      })
    }
  });
  transaction.commit();
  console.log(result);
  // TODO 发送通知

  let order = (await db.collection('order').doc(orderid).field({
    'customer.openid': true
  }).get()).data;
  console.log(order);
  let msg = {
    touser: order.customer.openid,
    templateId: 'pKxDj_0m_42i2_0d2R1K0pWQwV1iukPZVAOx3pLFOFs',
    miniprogram_state: 'trial',
    page: `/pages/user/order/detail/detail?_id=${order._id}`,
    data: {
      date2: {
        value: agenda.date + ' ' + agenda.time
      },
      thing3: {
        value: agenda.location
      },
      thing6: {
        value: agenda.service
      },
      thing4: {
        value: agenda.remark || '请注意拍摄时间'
      }
    }
  };
  await sendMessage(msg);

  return {
    success: true
  }
}


sendMessage = async (msg) => {
  const appid = "wx53f453674085a5ce";
  const secret = "346b6f46c964a24b6498e6784aff0d04";
  const url = `https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=${appid}&secret=${secret}`;
  let token = (await got.get(url, {
    responseType: 'json'
  })).body;
  console.log(token);

  // TODO 发消息
  const callUrl = `https://api.weixin.qq.com/tcb/invokecloudfunction?access_token=${token.access_token}&env=easyphoto-user-7gb3o971d6433059&name=sendMsg`;
  let res = (await got.post(callUrl, {
    json: msg
    // form: false,
    // json: true
  })).body;
  console.log(res);
  return res;
}

// 云函数入口函数
exports.main = async (event, context) => {
  const wxContext = cloud.getWXContext()

  switch (event.op) {
    case 'get':
      return getAgenda(event);
    case 'add':
      return addAgenda(event);
    case 'update':
      return await setAgenda(event);
  }
}